package com.tanhua.service;

import com.tanhua.domain.db.Question;
import com.tanhua.domain.db.User;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Comment;
import com.tanhua.domain.mongo.RecommendUser;
import com.tanhua.domain.vo.*;
import com.tanhua.dubbo.api.QuestionApi;
import com.tanhua.dubbo.api.RecommendUserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.UserLocationApi;
import com.tanhua.pojo.IMessage;
import com.tanhua.template.HuanXinTemplate;
import com.tanhua.util.UserHolder;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class RecommendUserService {
    @Reference
    private RecommendUserApi recommendUserApi;
    @Reference
    private UserInfoApi userInfoApi;
    @Reference
    private QuestionApi questionApi;
    @Reference
    private UserLocationApi userLocationApi;
    @Autowired
    private HuanXinTemplate huanXinTemplate;


    public ResponseEntity todayBest() {
        User user = UserHolder.getUser();
        RecommendUser recommendUser = recommendUserApi.findTodayBest(user.getId());
        if (recommendUser==null){
             recommendUser = new RecommendUser();
            recommendUser.setUserId(1L);
            recommendUser.setScore(98D);
        }
        UserInfo userInfo = userInfoApi.findUserInfo(recommendUser.getUserId());
        RecommendUserVO recommendUserVO = new RecommendUserVO();
        BeanUtils.copyProperties(userInfo,recommendUserVO);
        if (userInfo.getTags()!=null){
            recommendUserVO.setTags(userInfo.getTags().split(","));
            recommendUserVO.setFateValue(recommendUser.getScore().intValue());
        }
        return ResponseEntity.ok(recommendUserVO);
    }

    public ResponseEntity recommendation(RecommendUserQueryVO queryVO) {
        User user = UserHolder.getUser();
        //如果当前用户并没有推荐的用户则自己定义一些
        PageResult pageResult =  recommendUserApi.findRecommendation(user.getId(),queryVO.getPage(),queryVO.getPagesize());
        List<RecommendUser> items = pageResult.getItems();
        if (items==null||items.size()==0){
             items = new ArrayList<>();
            Long[] ids = {1l,2l,3l,4l,5l,6l,7l,8l,9l,10l,11l};
            for (Long id : ids) {
                RecommendUser recommendUser = new RecommendUser();
                recommendUser.setUserId(id);
                recommendUser.setScore(100D-id);
                items.add(recommendUser);
            }
            pageResult.setCounts(11);
            pageResult.setPages(2);
        }
        //把items里的数据转换为客户端需要的VO对象
        ArrayList<RecommendUserVO> vos = new ArrayList<>();
        for (RecommendUser recommendUser : items) {
            UserInfo userInfo = userInfoApi.findUserInfo(recommendUser.getUserId());
            RecommendUserVO vo = new RecommendUserVO();
            BeanUtils.copyProperties(userInfo,vo );
            if (userInfo.getTags()!=null){
                vo.setTags(userInfo.getTags().split(","));
            }
            vo.setFateValue(recommendUser.getScore().intValue());
            vos.add(vo);
        }
        pageResult.setItems(vos);

        return ResponseEntity.ok(pageResult);
    }

    /**
     * 查看佳人信息
     * @param targetUserId
     * @return
     */
    public ResponseEntity personalInfo(Long targetUserId) {
        User user = UserHolder.getUser();
        RecommendUser recommendUser = recommendUserApi.personalInfo(targetUserId,user.getId());
        UserInfo userInfo = userInfoApi.findUserInfo(targetUserId);
        RecommendUserVO vo = new RecommendUserVO();
        BeanUtils.copyProperties(userInfo,vo);
        if (userInfo.getTags()!=null){
            vo.setTags(userInfo.getTags().split(","));
        }
        vo.setFateValue(66);
        return ResponseEntity.ok(vo);
    }

    /**
     *查看陌生人信息
     * @param userId
     * @return
     */
    public ResponseEntity strangerQuestions(Long userId) {
        Question question = questionApi.findQuestion(userId);
        if (question!=null){
            return ResponseEntity.ok(question.getTxt());
        }
        return ResponseEntity.ok("你喜欢我吗?");
    }

    /**
     * 回复陌生人信息
     * @param userId
     * @param reply
     * @return
     */

    public ResponseEntity answerQuestions(Long userId, String reply) {
        //1. 查询当前用户的详细信息
        UserInfo userInfo = userInfoApi.findUserInfo(UserHolder.getUser().getId());

        //2. 查询目标用户的陌生人问题
        Question question = questionApi.findQuestion(userId);

        //3. 封装成环信的消息对象，发送消息给对方
        IMessage message = new IMessage();
        message.setUserId(userInfo.getId().toString());
        message.setNickname(userInfo.getNickname());
        message.setStrangerQuestion(question==null?"你喜欢我吗？":question.getTxt());
        message.setReply(reply);
        huanXinTemplate.sendMessage(userId.toString(), message);
        return ResponseEntity.ok(null);
    }

    public ResponseEntity search(String gender, Integer distance) {
        //1. 获取当前用户id
        Long userId = UserHolder.getUser().getId();
        //2. 调用API，搜索附近的人
        List<UserLocationDTO> locationDTOList = userLocationApi.searchNear(userId, distance);
        //3. 转换成VO，并排除性别不符合的人
        List<NearUserVO> voList = new ArrayList<>();
        for (UserLocationDTO userLocation : locationDTOList) {
            //排除自己
            if (userId.intValue() == userLocation.getUserId()) {
                continue;
            }

            //查找附近的人的详细信息
            UserInfo userInfo = userInfoApi.findUserInfo(userLocation.getUserId());
            //排除性别不符合的人
            if (!gender.equals(userInfo.getGender())) {
                continue;
            }

            NearUserVO vo = new NearUserVO();
            vo.setUserId(userInfo.getId());
            vo.setAvatar(userInfo.getAvatar());
            vo.setNickname(userInfo.getNickname());
            voList.add(vo);
        }
        return ResponseEntity.ok(voList);
    }
}
